29. Spring1 - 简单示例

简单示例

加入JAR包

​ ① Spring自身JAR包:spring-framework-4.0.0.RELEASE\libs目录下
​ spring-beans-4.0.0.RELEASE.jar
​ spring-context-4.0.0.RELE2ASE.jar
​ spring-core-4.0.0.RELEASE.jar
​ spring-expression-4.0.0.RELEASE.jar
​ ② commons-logging-1.1.1.jar

创建 conf source floder

创建 Spring 配置文件

2) 在Spring Tool Suite工具中通过如下步骤创建Spring的配置文件
​ ① File->New->Spring Bean Configuration File
​ ② 为文件取名字 例如:applicationContext.xml

创建 Pserson 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.itguigu.spring.mod;

public class Person {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + "]";
}
public Person(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Person() {
super();
}
}

Spring 配置文件进行 Bean 配置

applicationContext.xml 进行配置

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="person" class="com.itguigu.spring.mod.Person">
<property name="id" value="1001"></property>
<property name="name" value="zhangsan"></property>
</bean>
</beans>

获取 Bean 中配置的对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.itguigu.spring.mod;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBySpring {
public static void main(String[] args) {
// 获取Spring 所管理的 bean
// 1. 根据xml文件初始化容器
ApplicationContext aContext = new ClassPathXmlApplicationContext("applicationContext.xml");

// 2. 获取对象
Person person = (Person) aContext.getBean("person");
System.out.println(person); // Person [id=1001, name=zhangsan]
}
}

代码地址